package com.sne.security;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.sne.sys.service.ISysUserService;
import com.sne.sys.vo.SysUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author fanghh
 * @since 2020/1/3
 */
@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService iSysUserService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUserVO sysUserVO = iSysUserService.findByName(userName);
        if (ObjectUtils.isEmpty(sysUserVO)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        Set<String> grantedAuthoritySet = new HashSet<>();
        if (CollectionUtils.isNotEmpty(sysUserVO.getRoles())) {
            grantedAuthoritySet.addAll(sysUserVO.getRoles().stream()
                    .map(x -> "role_" + x.getRoleCode())
                    .collect(Collectors.toSet()));
        }
        if (CollectionUtils.isNotEmpty(sysUserVO.getMenus())) {
            Set<String> permissionSet = new HashSet<>();
            sysUserVO.getMenus().forEach(x -> {
                if (StringUtils.isNotBlank(x.getPermissionCode())) {
                    permissionSet.add(x.getPermissionCode());
                }
            });
            grantedAuthoritySet.addAll(permissionSet);
        }
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(grantedAuthoritySet.toArray(new String[0]));
        return new User(sysUserVO.getUserName(), sysUserVO.getPassword(), authorityList);
    }
}
